
webix.ready(function(){
	var projects = JSON.parse($("#projects").val());
	var cutterspescs = JSON.parse($("#projects").val());
	
	webix.ui.fullScreen();
  var my_template={
    template: "<span style='font-size:20px; font-weight:bold; color:#3498DB'; >刀具寿命阶梯数据查询</span>&nbsp;/&nbsp;&nbsp; CutterLife",
    height:45,
    borderless:true 
  };
  var my_table={
        view:"datatable",
        id:"mydatatable",
        columns:[
          {id:"interval",header:"寿命区间",fillspace:true},
          {id:"num",header:"数量",fillspace:true},
          {id:"percentage",header:"百分比",fillspace:true},
      ],
        height:600,
        select:true,
      
      };
      var my_toolbar={
        view:"toolbar",
        elements:[           
          {
        	view : "combo",
			id : "project_id",
			label : "选择项目",
			width : 320,
			labelWidth : 80,
			options : projects.data,
			on:{
	              'onChange':function(id){
	            	var project_id = $$("project_id").getValue();
	            	var params ={"project_id" : project_id}
	            	webix.ajax().sync().post("getCutterSpecsListByProjectId", params, function(text, xml, xhr) {
	            		var rs = JSON.parse(text);
	            		$$("my_pro_dt").clearAll();
	           			$$("material_id").define("options",rs.data)
	           			$$("my_pro_dt").refresh();
	            	});
	                
	              }
	            }
          },{
        	view : "combo",
			id : "material_id",
			label : "选择规格",
			labelWidth : 80
          },
          {
        	view : "datepicker",
			id : "startDate",
			timepicker : true,
			label : "开始日期",
			labelAlign : "right",
			name : "startDate",
			stringResult : true,
			format : "%Y-%m-%d",
			width : 240
          },
          {
          	view : "datepicker",
			id : "endDate",
			timepicker : true,
			label : "结束日期",
			labelAlign : "right",
			name : "endDate",
			stringResult : true,
			format : "%Y-%m-%d",
			width : 240
          },
          {view:"button",value:"查询",width:50,click:"select",css:"btn_check"},
          {view:"button",value:"查看区间",width:100,click:"addCutterSpecsIntervalShow",css:"btn_check"}
          

        ]   
      };
    var page={
            view:"pager",
            id:"pagerA",
            template:"{common.first()}{common.prev()}{common.pages()}{common.next()}{common.last()}",
            css:"pager",
            on: {
                  onItemClick: function(id, e, node){
                   if (id == "next") {
                    if($$("pagerA").config.limit==$$("pagerA").config.page+1)
                      {
                        id = $$("pagerA").config.limit-1;
                      }
                      else
                      {
                        id=$$("pagerA").config.page+1;
                      }
                    }
                  else if(id=="prev")
                  {
                    id=$$("pagerA").config.page-1; 
                  }
                  else if(id=="first")
                  {
                    id=0;
                  }
                  else if(id=="last")
                  {
                    id=$$("pagerA").config.limit-1;
                  } 
                }
            },
            height:38,
            css:{"text-align": "center","margin-top":"20px!important"}
        };

  var web={
    container:"body",
    type:"line",
    id:"mylayout",
    rows:[
        my_template,
        my_toolbar,
        my_table,
        page
    ],
  };
  webix.ui(web);// ---webix.ui结束----

//------------------  添加使用寿命区间   start------------------------
	var addForm = [ {
		id:"addMill",
		view : "button",
		value : "添加",
		width : 80,
		click : "addRows",
		css : {
			"margin-left" : "380px!important"
		}
	},{
	    view:"datatable",
	    id:"my_pro_dt",  
	    width:300, 
	    height:300, 
	    columns:[
	      {id:"startNum",header:"起始数",editor:"text",width:180},
	      {id:"endNum",header:"终止数",editor:"text",width:180},
	      {
	          id: "operate",
	          header: "操作",
	          width: 80,
	          tooltip: false,
	          fillspace: true,
	          template: "<button class='delbtn1 style'>删除</button>"
	      }/* {common.trashIcon()}删除 */
	    ],  
	    onClick: {// 删除规格寿命事件
	      "delbtn1": function(e, id, trg) {// list_index指选中的工序
	    	  $$("my_pro_dt").editStop();
	          $$("my_pro_dt").remove(id); 
	        return false;
	      } 
	    },     
	    select:true,
	    data:"",
	    editable:true,
	    tooltip:true
	  },{
		id:"addSub",
		view : "button",
		value : "确定",
		width : 80,
		click : "addSub",
		css : {
			"margin-left" : "380px!important"
		}
	}];
	var head = {
		view : "toolbar",
		margin : -4,
		cols : [ {
			view : "label",
			label : "查看使用寿命区间"
		}, {
			view : "icon",
			icon : "times-circle",
			click : "$$('win3').hide();"
		} ]
	};
	var body = {
		view : "form",
		id : "form",
		autoheight : true,
		width : 500,
		margin : 20,
		elements : addForm
	};
	var addMarkWindow = new webix.ui({
		view : "window",
		id : "win3",
		position : "center",
		modal : true,
		move : true,
		head : head,
		body : body
	});
	//------------------  添加打标计划窗口   end------------------------
})


var flag=true;
// 行id
var row;
// 添加一行
function addRow(){ 
	var dt=$$("mydatatable");
	if(flag){
	 var id=dt.add({
	 }); 
	 row=id;
	 console.log(row);
	 dt.addRowCss(id, "newRow");
	 dt.editRow(id);
	 flag=false;
	}else{
	 alert("请完成当前刀具添加");
	 console.log(row);
	 dt.editRow(row);
	}
};

// 查询实现
function select(){
  var params = {};
  
  var s1 = $$("material_id").getValue();
  var s2 = $$("startDate").getValue();
  var s3 = $$("endDate").getValue(); 
  var s4 = $$("project_id").getValue();
  if(s1 == ""){
	  alert("请选择刀具规格");
	  return;
  }
  if(s2 == ""){
	  alert("请选择开始时间");
	  return;
  }
  if(s3 == ""){
	  alert("请选择结束时间");
	  return;
  }
  if(s4 == ""){
	  alert("请选择项目");
	  return;
  }
  var bool=s2<=s3;
  if(s2==""||s3==""||bool==false){
	  alert("结束时间不能小于开始时间！");
	  return;
  }
  params.material_id = s1;
  params.startDate = s2.substr(0,10);
  params.endDate = s3.substr(0,10);
  params.project_id = s4;
  postData("getCutterLife",params,callback);
  
}

function callback(data){
	  var text1 = JSON.parse(data); 
 	  $$("mydatatable").clearAll();
	  $$("mydatatable").define("data",text1.data);
	  $$('mydatatable').refresh();
}

function edit(gg){
  console.log(gg);
  if(gg){
	  var dt=$$("mydatatable");
	  dt.eachRow(function(row){
		if(dt.getItem(row).material_id==gg){
		  dt.editRow(row);
		  dt.addRowCss(row, "newRow2");
		}    
	  });
  }
}


//添加使用寿命区间
function addCutterSpecsIntervalShow(){ 
	var material_id = $$("material_id").getValue();
	if(material_id == ""){
		alert("请选择刀具规格");
		return;
	}
	$("#edit_material_id").val(material_id);
	
	$$('win3').show();
	var params ={"material_id" : material_id}
	webix.ajax().sync().post("getCutterSpecsInterval", params, function(text, xml, xhr) {
		 var rs = JSON.parse(text);
		 if(rs.ret == "1000"){
			 var data = JSON.parse(rs.data);
			 $$("my_pro_dt").clearAll();
			 $$("my_pro_dt").define("data",data.data);
			 $$("my_pro_dt").refresh();
         }else{
        	 alert("获取寿命区间失败");
        	 location.reload();
         }
	});
	
};

/* 点击“添加”按钮添加一行 */
function addRows(){ 
  var dt=$$("my_pro_dt");  
  dt.enable();
  var id = dt.add({
  });
  dt.select(id);
  dt.editRow(id);
}

// 提交使用寿命区间
function addSub(){
	$$("addSub").disable();
	var num = 0;
	var start_judge=[];
	var end_judge=[];
	var start_nullValue=0;
	var end_nullValue=0;
	var csiList = [];
	/* 表格数据 */
	$$("my_pro_dt").eachRow( function (row){
		var dt=$$("my_pro_dt");
		start_judge.push(dt.getItem(row).startNum);
		end_judge.push(dt.getItem(row).endNum);
	});
	
	/* start_judge空值（""）数量 */
	for(var i=0;i<start_judge.length;i++){
		var re = /^[1-9]+[0-9]*]*$/;
		if (!re.test(start_judge[i]) && start_judge[i] != "0"){
			$$("addSub").enable();
			alert("起始数请输入正整数");  
		    return false;  
		}
		if((start_judge[i]==undefined||start_judge[i]=="") && start_judge[i]!="0"){
			console.log(start_judge[i]);
			start_nullValue++;
	    }
	};
	/* end_judge空值（""）数量 */
	for (var i = 0; i < end_judge.length; i++) {
		var re = /^[1-9]+[0-9]*]*$/;
		if (!re.test(end_judge[i])){
			$$("addSub").enable();
			alert("终止数请输入正整数");  
		    return false;  
		}
		if(end_judge[i]==undefined||end_judge[i]==""){
			end_nullValue++;
	    }
	};
	if(start_nullValue>0 || end_nullValue>0){
		webix.alert({
		      title:"警告",
		      text:"当前数据存在空值，请检查起始数，终止数！！",
		      ok:"确定",
		      type:"confirm-warning",
		      callback:function(result){
		        if(result==true){
		        }
		      }
		});
		$$("addSub").enable();
		return false;
	}else{
		$$("my_pro_dt").eachRow( function (row){
			var dt=$$("my_pro_dt");
			csiList[num] = {
	        		startNum: dt.getItem(row).startNum,
		            endNum: dt.getItem(row).endNum
		        };
			num++;
		});
	}
	var edit_material_id = $("#edit_material_id").val();
	
	var reData ={"reData" : JSON.stringify(csiList),"material_id" : edit_material_id}
	webix.ajax().sync().post("addCutterSpecsInterval", reData, function(text, xml, xhr) {
		 if(text == "success"){
        	 alert("保存成功");
        	 location.reload();
         }else{
        	 alert("保存失败");
        	 location.reload();
         }
		 
	});
}
